import java.util.LinkedList;
import java.util.Queue;

// https://leetcode.cn/problems/implement-stack-using-queues/submissions/
class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue1.offer(x);
    }
    
    public int pop() {
        int ret = -1;
        if (!queue1.isEmpty()) {
            while (queue1.size() != 1) {
                queue2.offer(queue1.poll());
            }
            ret = queue1.poll();
        } else {
            while (queue2.size() != 1) {
                queue1.offer(queue2.poll());
            }
            ret = queue2.poll();
        }
        return ret;
    }
    
    public int top() {
        int ret = -1;
        while (queue1.size() != 1 && !queue1.isEmpty()) {
            queue2.offer(queue1.poll());
            if (queue1.size() == 1) {
                ret = queue1.poll();
                queue2.offer(ret);
            }
        }
        while (queue2.size() != 1 && !queue2.isEmpty()) {
            queue1.offer(queue2.poll());
            if (queue2.size() == 1) {
                ret = queue2.poll();
                queue1.offer(ret);
            }
        }
        if (queue1.size() == 1 && queue2.size() != 1) {
            return queue1.peek();
        }
        if (queue2.size() == 1 && queue1.size() != 1) {
            return queue2.peek();
        }
        return ret;
    }
    
    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }

    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.empty());
    }
}